from django import forms
from django.shortcuts import render,redirect
from django.core.validators import RegexValidator
from django.core.paginator import Paginator
from django.conf import settings

from user_app import models
from utils.page import get_page
from utils import password_valid,bootstrap

class LoginForm(bootstrap.LoginModelForm):
    '''登录表单'''
    username = forms.CharField(label='用户名',max_length=16,min_length=2,widget=forms.TextInput)
    password = forms.CharField(label='密码',max_length=26,min_length=6,widget=forms.PasswordInput)

    class Meta:
        model = models.AdminUser
        fields = ['username','password']
        
    def clean_password(self):
        '''密码验证'''
        password = self.cleaned_data['password']
        #加密
        return password_valid.sha(password+settings.SECRET_KEY)
        
def login(request):
    '''登录'''
    if request.method == 'GET':
        form = LoginForm()
        return render(request, 'login.html',{'form': form})
    else:
        form = LoginForm(request.POST)
        if form.is_valid():
            # 获取用户名和密码
            data = form.cleaned_data
            user = models.AdminUser.objects.filter(**data).first()
            if user:
                # 登录成功，保存用户信息到session中
                request.session['user'] = data
                return redirect('/home/')
            else:
                form.add_error('password','用户名或密码错误')
                return render(request, 'login.html',{'form': form})
        else:
            return render(request, 'login.html',{'form': form})

def home(request):
    '''首页'''
    # 获取用户信息
    user = request.session.get('user')
    if not user:
        return redirect('/login/')
    else:
        return render(request, 'home.html',{'user':user})

def logout(request):
    '''退出登录'''
    try:
        del request.session['user']
        return redirect('/login/')
    except:
        return redirect('/login/'
)

def user_list(request):
    '''用户列表'''
    queryset = models.UserInfo.objects.all()
    return render(request, 'user.html',{'queryset':queryset})

class MyModelForm(forms.ModelForm):
    name = forms.CharField(label='姓名',required=True,min_length=2,max_length=10)
    age = forms.IntegerField(label='年龄',required=True,min_value=1,max_value=80)
    account = forms.CharField(label='账号',required=True,)
    create_time = forms.DateTimeField(label='入职时间',required=True)
    class Meta:
        model = models.UserInfo
        fields = ['name','age','gender','account','department','create_time']

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        for name,field in self.fields.items():
            #为每个字段设置样式
            field.widget.attrs = {'class':'form-control','placeholder':field.label}

def add_user(request):
    '''增加用户'''
    if request.method == 'GET':
        form = MyModelForm()
        return render(request, 'user_add.html',{'form' : form})
    else:
        form = MyModelForm(request.POST)
        if form.is_valid():
            form.save()
            return redirect('/user/list/')
        else:
            return render(request, 'user_add.html',{'form' : form})
        
def edit_user(request,nid):
    '''编辑用户'''
    obj = models.UserInfo.objects.get(pk=nid)
    if request.method == 'GET':
        form = MyModelForm(instance=obj)
        return render(request, 'user_add.html',{'form': form})
    else:
        # 修改用户,instance=obj,表示要修改的对象
        form = MyModelForm(request.POST,instance=obj)
        if form.is_valid():
            #save()默认保存的是用户输入的，如果想要班训其他数据，需要手动指定
            #form.instance.字段 = 值
            form.save()
            return redirect('/user/list/')
        else:
            return render(request, 'user_add.html',{'form': form})

def delete_user(request):
    '''删除用户'''
    if request.method == 'GET':
        try:
            nid = request.GET.get('nid')
            models.UserInfo.objects.get(pk=nid).delete()
            return redirect('/user/list/')
        except:
            return redirect('/user/list/')


# Create your views here.
def depart(request):
    '''部门列表'''
    queryset = models.Department.objects.all()
    return render(request, 'depart.html',{'queryset':queryset})

def add_depart(request):
    '''增加部门'''
    if request.method == 'GET':
        return render(request, 'depart_add.html',{'obj':''})
    else:
        title = request.POST.get('title')
        d_id = request.POST.get('d_id')
        if not title:
            return render(request, 'depart_add.html',{'error_msg':'部门名称不能为空!'})
        models.Department.objects.create(title=title,d_id=d_id)
        return redirect('/depart/list/')
    
def edit_depart(request,nid):
    '''编辑部门'''
    if request.method == 'GET':
        obj = models.Department.objects.get(pk=nid)
        return render(request, 'depart_edit.html',{'obj':obj})
    if request.method == 'POST':
        d_id = request.POST.get('d_id')
        title = request.POST.get('title')
        if not title:
            return render(request, 'depart_edit.html',{'error_msg':'部门名称不能为空!'})
        models.Department.objects.filter(pk=nid).update(title=title,d_id=d_id)
        return redirect('/depart/list/')

def delete_depart(request):
    '''删除部门'''
    if request.method == 'GET':
        try:
            nid = request.GET.get('nid')
            models.Department.objects.get(pk=nid).delete()
            return redirect('/depart/list/')
        except:
            return redirect('/depart/list/')
    else:
        return redirect('/depart/list/')
#测试时间插件
def test(request):
    return render(request, 'login.html')

class AdminModelForm(forms.ModelForm):
    username = forms.CharField(label='管理员账户',required=True,error_messages={'required':'账户不能为空'})
    password = forms.CharField(label='管理员密码',required=True,error_messages={'required':'密码不能为空'},
                               widget=forms.PasswordInput,min_length=6,max_length=10,validators=[
        RegexValidator(r'^[0-9a-zA-Z]{6,12}$', '请输入6-12位数字或字母')
    ])
    confirm_password = forms.CharField(label='确认密码',required=True,error_messages={'required':'确认密码不能为空'},min_length=6,max_length=10,
                                       widget=forms.PasswordInput)
    class Meta:
        model = models.AdminUser
        fields = '__all__'
        
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        for name,field in self.fields.items():
            '''
            username <django.forms.fields.CharField object at 0x0000016EF0517BD0>
            password <django.forms.fields.CharField object at 0x0000016EF0517E10>
            '''
            #为每个字段设置样式
            field.widget.attrs = {'class': 'form-control', 'placeholder': field.label}          

def admininfo(request):
    #参数获取
    params = dict(request.GET)
    query = request.GET.get('query_param','')
    page_num = int(request.GET.get('page',1))
    queryset = models.AdminUser.objects.filter(username__contains=query).order_by('-id')
    #判断是否有分页条件
    if params.get('page'):
        del params['page']
    #拼接参数url
    #判断是否有搜索条件
    str_param = ''
    if params:
        str_param = '&'.join([f'{k}={v[0]}' for k, v in params.items()]) + '&'
    #分页处理
    paginator = Paginator(queryset, settings.PAGE_SIZE)
    #分页序列
    page_range = get_page(page_num,paginator.num_pages, settings.PAGE_MIDDLE_DATA)
    #获取当前页的数据
    page_data = paginator.get_page(page_num)
    return render(request, 'admininfo.html',{'queryset':page_data, 'params': str_param,'query':query,'page_range': page_range, 'cur_num': page_num})

def add_admin(request):
    if request.method == 'GET':
        #传一个空的过去，渲染输入框
        form = AdminModelForm()
        return render(request, 'admininfo_add.html',{'form': form})
    else:
        #单独保存一个用户
        form = AdminModelForm(data = request.POST)
        #cleaned_data可以取出表单中的数据
        password = form['password'].data
        pwd = password_valid.sha(password+settings.SECRET_KEY)
        if form.is_valid():
            #save()默认保存的是用户输入的，如果想要班训其他数据，
            #需要手动指定，form.instance.字段 = 值
            form.instance.password = pwd
            form.save()
            return redirect('/ad/list/')
        return render(request, 'admininfo_add.html',{'form': form})

class AdminEditModelForm(forms.ModelForm):
    username = forms.CharField(label='管理员账户',required=True,error_messages={'required':'账户不能为空'})
    
    class Meta:
        model = models.AdminUser
        fields = ['username']
        widgets = {'username': forms.TextInput(attrs={'class':'form-control',"placeholder":'管理员账户'})}
        
def edit_admin(request,nid):
    obj = models.AdminUser.objects.get(pk=nid)
    form = AdminEditModelForm(instance=obj)
    if request.method == 'GET':
        return render(request, 'admininfo_edit.html',{'form': form})
    else:
        form = AdminEditModelForm(data=request.POST,instance=obj)
        if form.is_valid():
            form.save()
            return redirect('/ad/list/')
        return render(request, 'admininfo_edit.html',{'form': form})
        
def delete_admin(request,nid):
    if request.method == 'GET':
        models.AdminUser.objects.get(pk=nid).delete()
        return redirect('/ad/list/')

class ResetModelForm(forms.ModelForm):
    password = forms.CharField(label='管理员密码',required=True,error_messages={'required':'密码不能为空'},
                               widget=forms.PasswordInput,min_length=6,max_length=16)
    confirm_password = forms.CharField(label='确认密码',required=True,error_messages={'required':'确认密码不能为空'},
                                       widget=forms.PasswordInput,min_length=6,max_length=16)
    class Meta:
        model = models.AdminUser
        fields = ['password', 'confirm_password']
    
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        for name,field in self.fields.items():
            #为每个字段设置样式
            field.widget.attrs = {'class': 'form-control', 'placeholder': field.label}          
        
    def clean_password(self):
        password = self.cleaned_data['password']
        va_pwd = password_valid.sha(password+settings.SECRET_KEY)
        b = models.AdminUser.objects.filter(pk=self.instance.id,password=va_pwd).exists()
        if b:
            raise forms.ValidationError('不能与之前密码相同')
        return va_pwd
        
def reset_admin(request,nid):
    obj = models.AdminUser.objects.get(pk=nid)
    if request.method == 'GET':
        if not obj:
            return redirect('/ad/list/')
        form = ResetModelForm()
        return render(request, 'admininfo_reset.html',{'form': form})
    else:
        form = ResetModelForm(data=request.POST,instance=obj)
        if form.is_valid():
            form.save()
            return redirect('/ad/list/')
        return render(request, 'admininfo_reset.html',{'form': form})
    
